import 'dart:async';

import 'package:aichat_flutter_wallet/kai_print.dart';
import 'package:aichat_flutter_wallet/module/module_user_info/widgets/fans_page_list.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/header/page_fans_header.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lib_database/lib_database.dart';
import 'package:lib_util/common/extentions.dart';

import '../../../module_common/bridge/native_channel_bridge.dart';
import '../../../module_common/widgets/page_status_com.dart';
import '../../../module_common/widgets/public_tip/public_tip.dart';
import '../model/user_info_api.dart';
import '../model/user_info_model.dart';
import '../widgets/sliver_fans_delegate.dart';

class FansPage extends StatefulWidget {
  String fansTabsType;
  String title;
  String userId;
  FansPage({super.key, this.fansTabsType = 'Follow',this.title='',this.userId=''});

  @override
  State<FansPage> createState() => FansPageState();
}

class FansPageState extends State<FansPage> with TickerProviderStateMixin {
  late ScrollController _scrollController;
  late ScrollController _scrollController2;
  late TabController _tabController;
  String title='';

  TextEditingController _textEditingController = TextEditingController();
  FocusNode _focusNode = FocusNode();
  int _currentIndex = 0 ;

  get fansTabsType => widget.fansTabsType;

  // 头部选项 tabs
  List<FansTabsItemType> tabs = [
    FansTabsItemType(
        name: 'Follow',
        value: FansTabsType.Follow,
        num: -1,
        searchNum: -1,
        totalPage: 1,
        page: 1,
        totalSearchPage: 1,
        searchPage: 1,
        searchText: '',
        size: 15,
        isLoading: false,
        isSearchLoading: false,
        searchData:[],
        data: []),
    FansTabsItemType(
      searchNum: -1,
        num: -1,
        page: 1,
        searchPage: 1,
        searchText:'',
        size: 15,
        name: 'Fans',
        value: FansTabsType.Fans,
        isLoading: false,
        isSearchLoading: false,
        data: [],
        searchData:[],),
  ];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _scrollController = ScrollController();
    _scrollController2 = ScrollController();
    _tabController = TabController(length: tabs.length, vsync: this);
    _tabController.addListener((){
      // 重置页面参数
      _focusNode.unfocus();
      _textEditingController.text= '';
      tabs[0].searchText='';
      tabs[0].page=1;
      tabs[0].searchPage=1;
      tabs[0].data = callbackFilterPageOneData(tabs[0].data);
      tabs[0].searchData = callbackFilterPageOneData(tabs[0].searchData);
      tabs[1].searchText='';
      tabs[1].page=1;
      tabs[1].searchPage=1;
      tabs[1].data = callbackFilterPageOneData(tabs[1].data);
      tabs[1].searchData = callbackFilterPageOneData(tabs[1].searchData);
      _handleTabSelection();
    });
    initPage();
    // 获取 sp 的签到信息
  }

  List<FansTabsItemDataType> callbackFilterPageOneData(List<FansTabsItemDataType> data){
    List<FansTabsItemDataType> result=[];
    if(data.length>0){
      result = [...data].sublist(0, (data.length >= 15 ? 15 : 15.clamp(0, data.length)));
    }
    return result;
  }


  List<FansTabsItemDataType> callbackFollowData(List<FollowListItem> lists){
    List<FansTabsItemDataType> result= [];
    for(var i=0;i<lists.length;i++){
      var item = lists[i];
      result.add(FansTabsItemDataType(
        title: item.nickname,
        describe: item.brief,
        userId: item.user_id,
        icon: item.profile_picture,
        isFriend: item.is_friend,
        status: item.status
      ));
    }
    return result;
  }


  void _handleTabSelection({Completer? completer})  {
    try {
      final index= _tabController.index;
      _currentIndex = index;
      if(tabs[index].isLoading){
        return;
      }
      tabs[index].isLoading=true;
      UserInfoApi.getFollowList(
        userId: widget.userId,
          scene: tabs[index].value,
          page: tabs[index].page,
          size:tabs[index].size).then((resp) async{
        int total=int.parse(resp!.count);
        final result=callbackFollowData(resp.list);
        tabs[index].num= total;
        tabs[index].totalPage= total ~/ tabs[index].size + (total % tabs[index].size>0?1:0);
        if(tabs[index].page==1){
          tabs[index].data=result;
        }else{
          tabs[index].data=[...tabs[index].data,...result];
        }
        tabs[index].isLoading=false;
        if(mounted)setState(() {});
        if(tabs[index].page==1){
          // final userId = NativeChannelBridge.instance.appCommMsg?.userId;
          await SP().setFansListData(result,'${index.toString()}_${widget.userId}');
        }
        if(completer!=null){
          completer.complete(true);
        }
      }).catchError((_){
        Toast.show(context, message: "Network abnormality, please try again later",status: '-1',position: Dpositon.top);
        tabs[index].isLoading=false;
        if(mounted)setState(() {
        });
        if(completer!=null)completer.complete(true);
      });
    } catch (e) {
      kaiPrint('_handleTabSelection $e');
    }
  }


  void _handleSearch({Completer? completer})  {
    try {
      final index= _tabController.index;
      _currentIndex = index;
      if(tabs[index].isSearchLoading){
        return;
      }
      tabs[index].isSearchLoading=true;
      UserInfoApi.getFollowList(
          userId: widget.userId,
          keyword: tabs[index].searchText,
          scene: tabs[index].value,
          page: tabs[index].searchPage,
          size:tabs[index].size).then((resp) async{
        final result=callbackFollowData(resp!.list);
        tabs[index].searchNum=result.length;
        if(tabs[index].searchPage==1){
          tabs[index].searchData=result;
        }else{
          tabs[index].searchData=[...tabs[index].searchData,...result];
        }
        tabs[index].isSearchLoading=false;
        tabs[index].totalSearchPage= result.length ~/ tabs[index].size + (result.length % tabs[index].size>0?1:0);
        if(mounted)setState(() {
        });
        if(completer!=null){
          completer.complete(true);
        }
      }).catchError((_){
        Toast.show(context, message: "Network abnormality, please try again later",status: '-1',position: Dpositon.top);
        tabs[index].isSearchLoading=false;
        if(mounted)setState(() {
        });
        if(completer!=null)
          completer.complete(true);
      });
    } catch (e) {
      kaiPrint('_handleTabSelection $e');
    }
  }

  @override
  void dispose() {
    /// 取消路由订阅
    super.dispose();
    _focusNode.unfocus();
    _focusNode.dispose();
    _textEditingController.dispose();
    _scrollController.dispose();
    _scrollController2.dispose();
    _tabController.dispose();
  }

  initSPData(String uId){
    for(var i=0;i<tabs.length;i++){
      final tab = SP().getFansListData(i.toString()+'_'+uId);
      if(tab.isNotEmpty){
        tabs[i].data = tab;
      }
    }
    if (mounted) setState(() {});
  }

  initPage({String? params,String? userName,String? uid}) async {
    if(params != null){
      _currentIndex = (params == 'Follow' ? 0 : 1);
      title= (userName==null?'':userName);
      widget.userId = uid!;
    }else{
      _currentIndex = (fansTabsType == 'Follow' ? 0 : 1);
      title= widget.title;
    }
    _tabController.index = _currentIndex;

    final userId = NativeChannelBridge.instance.appCommMsg?.userId;
    if(mounted) setState(() {});
    if (userId != '0' && userId != null && userId.isNotEmpty) {
      initSPData(widget.userId);
      // 获取 关注列表数据
      tabs[0].searchText='';
      tabs[1].searchText='';
      tabs[0].page=1;
      tabs[1].page=1;
      _handleTabSelection();
      final otherListIndex=_tabController.index == 0?1:0;
      tabs[otherListIndex].isLoading=true;
      // 获取 粉丝列表数据
      UserInfoApi.getFollowList(
          scene: tabs[otherListIndex].value,
          page: tabs[otherListIndex].page,
          size: tabs[otherListIndex].size,
          userId: widget.userId
      ).then((resp) async {
        final total=int.parse(resp!.count);
        final result = callbackFollowData(resp.list);
        tabs[otherListIndex].num=total;
        tabs[otherListIndex].totalPage= total ~/ tabs[otherListIndex].size + (total % tabs[otherListIndex].size>0?1:0);
        tabs[otherListIndex].data=result;
        tabs[otherListIndex].isLoading=false;
        if(mounted)setState(() {
        });
        if(tabs[otherListIndex].page==1){
          // final userId = NativeChannelBridge.instance.appCommMsg?.userId;
          await SP().setFansListData(result,'${otherListIndex}_${widget.userId}');
        }
      });
    }

  }

  List<Widget> getTabs() {
    return tabs
        .map((e) => Container(
              margin: EdgeInsets.only(left: 0.w, right: 0.w),
              height: 50.w,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: Colors.transparent,
                borderRadius: BorderRadius.circular(0.w), // 设置圆角半径为 10.0
              ),
              child: Text(
                e.name + ' (${(e.num==-1?0:e.num).toString()})',
                overflow: TextOverflow.visible,
                softWrap: false,
                style: TextStyle(fontSize: 16.w, fontWeight: FontWeight.w500),
              ),
            ))
        .toList(growable: false);
  }

  //搜索点击框
  Widget searchTextFieldBar() {
    return Container(
      height: 36.w,
      margin: EdgeInsets.only(left: 20.w, right: 20.w, top: 15.w),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10.w),
          color: '#F6F6F6'.toColor()),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          SizedBox(width: 15.w),
          Image.asset(
            'assets/images/dapp/search.png',
            width: 20.w,
            height: 20.w,
          ),
          SizedBox(width: 10.w),
          Expanded(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Expanded(
                    child: Stack(children: [
                  TextField(
                    style: TextStyle(
                        fontSize: 14.sp,
                        textBaseline: TextBaseline.ideographic,
                        height: (1.1).w),
                    cursorHeight: 16.w,
                    controller: _textEditingController,
                    focusNode: _focusNode,
                    maxLines: 1,
                    minLines: 1,
                    cursorColor: Color.fromRGBO(134, 103, 254, 1),
                    cursorWidth: 1.5.w,
                    onEditingComplete: () {
                      // 处理 "done" 键事件
                      _focusNode?.unfocus();
                      tabs[_currentIndex].searchPage=1;
                      _handleSearch();
                    },
                    onChanged: (value) {
                      tabs[_currentIndex].searchText=value;
                      // setState(() {});
                    },
                    onTapOutside: (even) {
                      _focusNode?.unfocus();
                      tabs[_currentIndex].searchPage=1;
                      _handleSearch();
                      //拿到删除按钮，判断点击的是否删除按钮，是的话不需要收起软键盘
                    },
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      hintText: 'Search',
                      contentPadding: EdgeInsets.only(bottom: 12.w),
                      hintStyle: TextStyle(
                        fontSize: 14.sp,
                        height: 1.01.w,
                        textBaseline: TextBaseline.ideographic,
                        color: Color.fromRGBO(190, 189, 202, 1),
                      ),
                    ),
                  )
                ])),
              ],
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: PageFansHeaderCom(
          title: title,
          showBottomBorder: false,
          definedGoBack: true,
          goBack: () {
            NativeChannelBridge.instance.closeFlutterPage(num: 1);
          }),
      body: CustomScrollView(
        controller: _scrollController2,
        physics: const NeverScrollableScrollPhysics(),
        slivers: [
          SliverPersistentHeader(
              pinned: true,
              delegate: SliverFansDelegate(
                  isEmpty: true,
                  search: searchTextFieldBar(),
                  tabBar: TabBar(
                    overlayColor: MaterialStateProperty.resolveWith<Color?>(
                      (Set<MaterialState> states) {
                        if (states.contains(MaterialState.hovered)) {
                          // 悬停时的覆盖颜色
                          return Colors.transparent;
                        } else if (states.contains(MaterialState.pressed)) {
                          // 按下时的覆盖颜色
                          return Colors.transparent;
                        }
                        // 默认状态下的覆盖颜色
                        return Colors.transparent; // 或者返回你想要的颜色
                      },
                    ),
                    dividerColor: Colors.transparent,
                    tabAlignment: TabAlignment.start,
                    isScrollable: true,
                    labelColor: Color.fromRGBO(5, 1, 1, 1),
                    unselectedLabelColor: Color.fromRGBO(190, 189, 202, 1),
                    indicatorColor: Color.fromRGBO(51, 51, 51, 1),
                    // indicatorWeight: 1,
                    indicator: UnderlineTabIndicator(
                      borderSide: BorderSide(
                        color: Color.fromRGBO(51, 51, 51, 1), // 下划线的颜色
                        width: 1.5.w, // 下划线的宽度
                      ),
                      insets: EdgeInsets.symmetric(horizontal: 0), // 下划线的水平间距
                    ),
                    indicatorPadding:
                        EdgeInsets.only(left: 0.w, right: 0.w, bottom: 1.w),
                    tabs: getTabs(),
                    labelPadding: EdgeInsets.only(left: 0.w, right: 30.w),
                    labelStyle:
                        TextStyle(fontWeight: FontWeight.w500, fontSize: 16.sp),
                    controller: _tabController,
                  ),
                  backgroundColor: Colors.transparent)),
          SliverFillRemaining(
            child: tabs[_currentIndex].data.isEmpty
                ? Container(
                    color: Colors.transparent,
                    child: PageEmptyCom(title: 'Empty data'),
                  )
                : Container(
                    color: Colors.transparent,
                    height: double.infinity,
                    child: TabBarView(
                        physics: NeverScrollableScrollPhysics(),
                        controller: _tabController,
                        children: tabs.map((element) {
                          return FansPageList(
                            title: element.name,
                            pageStatus: 1,
                            getMore: () {
                              final cIndex= _currentIndex;
                              final searchText = tabs[cIndex].searchText;
                              final Completer completer = Completer<bool>();
                              Future future = completer.future;
                              try{
                                if(searchText.isNotEmpty){
                                  if(tabs[cIndex].searchPage  > tabs[cIndex].totalSearchPage && tabs[cIndex].searchNum!=-1){
                                    completer.complete(true);
                                    return future.timeout(const Duration(seconds: 10000), onTimeout: () {
                                      throw 'request time out';
                                    });;
                                  }
                                  tabs[cIndex].searchPage=tabs[cIndex].searchPage+1;
                                  _handleSearch(completer:completer);
                                }else{
                                  if(tabs[cIndex].page  > tabs[cIndex].totalPage  && tabs[cIndex].num!=-1){
                                    completer.complete(true);
                                    return future.timeout(const Duration(seconds: 10000), onTimeout: () {
                                      throw 'request time out';
                                    });;
                                  }
                                  tabs[cIndex].page++;
                                  _handleTabSelection(completer:completer);
                                }
                                return future.timeout(const Duration(seconds: 10000), onTimeout: () {
                                  throw 'request time out';
                                });;
                              }catch(e){
                                return future.timeout(const Duration(seconds: 10000), onTimeout: () {
                                  throw 'request time out';
                                });;
                              }
                            },
                            list: element.searchText.isNotEmpty? element.searchData:element.data,
                            hasMore: true,
                            onClick: (FansTabsItemDataType item,int index) async {
                              try{
                                final userId = NativeChannelBridge.instance.appCommMsg!.userId;
                                final cIndex=_currentIndex;
                                final value= await UserInfoApi.postFollow(item.userId);
                                if(item.status==0&&value != -1&&value != -2){
                                  Toast.hide();
                                  Toast.show(context, message: "Follow the success",position: Dpositon.top);
                                  tabs[cIndex].data[index].status = value!;
                                  if(widget.userId == userId){
                                    if(value.toString()=='1' || value.toString()=='2'){
                                      tabs[cIndex].num +=1;
                                    }
                                    if(value.toString() == '0'){
                                      tabs[cIndex].num -=1;
                                    }
                                  }
                                  if(mounted)setState(() {});
                                  if(tabs[cIndex].data.length>0 && tabs[cIndex].page==1){
                                    await SP().setFansListData(tabs[cIndex].data,'${cIndex}_${widget.userId}');
                                  }
                                }else if([1,2].contains(item.status)&&value!=-1&&value != -2){
                                  String text= cIndex==0? "Unfollow" : "Follow the success";
                                  if(cIndex==1&&item.status==2){
                                    text='Unfollow';
                                  }
                                  if(cIndex==1&&item.status==1&&value.toString()=='0'){
                                    text='Unfollow';
                                  }
                                  Toast.hide();
                                  Toast.show(context, message: text,position: Dpositon.top);
                                  tabs[cIndex].data[index].status = value!;
                                  if(widget.userId == userId){
                                    if(value.toString() == '0'){
                                      tabs[cIndex].num -=1;
                                    }
                                  }
                                  if(mounted)setState(() {});
                                  if(tabs[cIndex].data.length>0 && tabs[cIndex].page==1){
                                    await SP().setFansListData(tabs[cIndex].data,'${cIndex}_${widget.userId}');
                                  }
                                }else if(value==-1){
                                  Toast.show(context, message: "Failed to follow, the user cannot be found",status: '-1',position: Dpositon.top);
                                }else if(value==-2){
                                  Toast.show(context, message: "Failed to follow, users cannot follow themselves",status: '-1',position: Dpositon.top);
                                }
                                return true;
                              }catch(e){
                                Toast.show(context, message: "Network abnormality, please try again later",status: '-1',position: Dpositon.top);
                                return true;
                              }
                            },
                          );
                        }).toList(growable: false)),
                  ),
          ),
        ],
      ),
    );
  }
}
